package com.jdew.thkj.fragment;

import android.app.Activity;
import android.content.SharedPreferences;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.BaoBiaoActivity;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/6/5.
 */

public class YestodayFragment extends BaseFragment {
    @Bind(R.id.profit)
    TextView profit;
    @Bind(R.id.bishu)
    TextView bishu;
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;
    private BaoBiaoActivity activity;
    private DecimalFormat df = new DecimalFormat("0.00");

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_today;
    }

    @Override
    protected void onCreateViewT() {
        activity = (BaoBiaoActivity) getActivity();
        sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        GetTodayMoney();
        GetPDDTodayMoney();
    }
    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String source){
        if(source.equals("tb")){
            activity.type=0;
            GetTodayMoney();
        }else if(source.equals("pdd")){
            activity.type=1;
            GetPDDTodayMoney();
        } else if(source.equals("jd")){
            activity.type=4;
            GetJDhMoney(4,"YesterDay");
        }
    }
    public void GetTodayMoney() {
        if (activity.type != 0) {
            return;
        }
        String date = getYestDay();
        String timesamp= RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTodayMoney(sp.getString("mpid", ""), date, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"Pid"+sp.getString("mpid", "")+"time"+date)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.e("sssssssssss", e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("0")) {
                    profit.setText("¥ " + df.format(Double.parseDouble(json.getString("data"))));
                    bishu.setText(json.getString("message") + " 笔");
                } else if (json.getString("code").equals("-1")) {
                    profit.setText("¥ 0.00");
                    bishu.setText("0 笔");
                }
                SpannableString spannableString = new SpannableString(profit.getText().toString());
                RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                spannableString.setSpan(sizeSpan, 1, profit.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                profit.setText(spannableString);
            }
        });
    }

    public void GetPDDTodayMoney() {
        if (activity.type != 1) {
            return;
        }

        String date = getYestDay();
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetPDDTodayMoney(sp.getString("userPhone", ""), date,RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"UserPhone"+sp.getString("userPhone", "")+"time"+date)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.e("sssssssssss", e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("0")) {
                    profit.setText("¥ " + df.format(Double.parseDouble(json.getString("data"))));
                    bishu.setText(json.getString("message") + " 笔");
                } else if (json.getString("code").equals("-1")) {
                    profit.setText("¥ 0.00");
                    bishu.setText("0 笔");
                }
                SpannableString spannableString = new SpannableString(profit.getText().toString());
                RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                spannableString.setSpan(sizeSpan, 1, profit.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                profit.setText(spannableString);
            }
        });
    }
    public void GetJDhMoney(int type, final String time) {
        if (type != 4) {
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap map = new HashMap();
        map.put("UserId", sp.getString("userId", ""));
        map.put("platForm", time);
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetJdMoney(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + sp.getString("userId", "")+"platForm"+time)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e("sssssssssss", e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("0")) {
                    String result = json.getString("data");
                    JSONObject obj=JSONObject.parseObject(result);
                    profit.setText("¥ " + df.format(Double.parseDouble(obj.getString("money"))));
                    bishu.setText(obj.getString("number") + " 笔");
                } else if (json.getString("code").equals("-1")) {
                    profit.setText("¥ 0.00");
                    profit.setText("¥ 0.00");
                }
                SpannableString spannableString = new SpannableString(profit.getText().toString());
                RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                spannableString.setSpan(sizeSpan, 1, profit.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                profit.setText(spannableString);
            }
        });
    }
    public String getYestDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        return sdf.format(date);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
